package netty.group;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by yu756 on 2020/1/6 22:40
 */
public class GroupChatServerHandler extends SimpleChannelInboundHandler<String> {

    // 点对点的聊天 使用HashMap 管理
    //  public static Map<String, Channel> channelMap = new HashMap<>();


    //定义一个channel 组。管理所有的channel
    // GlobalEventExecutor.INSTANCE 全局事件执行器是一个单例
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    SimpleDateFormat sdf = new SimpleDateFormat(("yyyy-MM-dd HH:mm:ss"));

    //建立连接的时候 第一个被执行的
    // 将当前channel 加入到channelGroup
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        // 将该客户加入聊天的信息推送给其他在线客户端   将channelGroup所有的channel遍历，并且发送消息
        channelGroup.writeAndFlush("[客户端]" + channel.remoteAddress() + "加入聊天" + sdf.format(new Date()) + "\n");
        channelGroup.add(channel);


        // channelMap.put("id001", channel);

    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        System.out.println(ctx.channel().remoteAddress() + "上线了");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + "离线了");
    }


    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        // 离线消息告诉其他客户端
        channelGroup.writeAndFlush("[客户端]" + ctx.channel().remoteAddress() + "加入聊天");
        System.out.println("channelGroup size" + channelGroup.size());
    }

    // 转发消息
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String msg) throws Exception {

        Channel channel = channelHandlerContext.channel();
        channelGroup.forEach(ch -> {
            if (channel != ch) {// 不是当前的channel就转发
                ch.writeAndFlush("{客户}" + channel.remoteAddress() + "发送消息" + msg + "\n");
            } else {
                ch.writeAndFlush("{自己}" + "发送消息" + msg + "\n");
            }


        });


    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 关闭通道
        ctx.close();
    }
}
